<template>
  <div class="bg-white rounded-2xl shadow-sm ring-1 ring-gray-200 p-6">
    <!-- 对话历史内容 -->
    <div v-if="activeTab === 'history'">
      <PageHeader 
        title="对话历史"
        search-placeholder="搜索对话记录..."
        @search="handleHistorySearch"
      />
      
      <HistoryList 
        :items="historyItems"
        :search-keyword="historySearchKeyword"
        @favorite="handleAddToFavorites"
        @open="handleOpenHistory"
      />
    </div>
    
    <!-- 我的收藏内容 -->
    <div v-else-if="activeTab === 'favorites'">
      <PageHeader 
        title="我的收藏"
        search-placeholder="搜索对话记录..."
        @search="handleFavoritesSearch"
      />
      
      <!-- 加载状态 -->
      <div v-if="favoritesLoading" class="text-center py-12">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[#635BFF]"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="favoritesError" class="text-center py-12">
        <p class="text-red-500">{{ favoritesError }}</p>
        <button @click="fetchFavorites" class="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
          重试
        </button>
      </div>
      
      <!-- 收藏列表 -->
      <FavoritesList 
        v-else
        :items="favoriteItems"
        :search-keyword="favoritesSearchKeyword"
        @remove="handleRemoveFromFavorites"
        @open="handleOpenFavorite"
      />
    </div>
    
    <!-- 自定义角色内容 -->
    <div v-else-if="activeTab === 'custom-roles'">
      <PageHeader 
        title="自定义角色"
        search-placeholder="搜索角色..."
        :show-create-button="true"
        @search="handleCustomRolesSearch"
        @create="handleCreateRole"
      />
      
      <!-- 加载状态 -->
      <div v-if="customRolesLoading" class="text-center py-12">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[#635BFF]"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="customRolesError" class="text-center py-12 text-red-500">
        <svg class="w-12 h-12 mx-auto mb-4 text-red-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
        </svg>
        <p class="mb-4">{{ customRolesError }}</p>
        <button 
          @click="fetchCustomRoles()"
          class="h-10 px-4 rounded-lg bg-[#635BFF] text-white hover:bg-[#5a4fcf] transition-colors"
        >
          重试
        </button>
      </div>
      
      <!-- 正常内容 -->
      <CustomRolesList 
        v-else
        :items="customRolesItems"
        :search-keyword="customRolesSearchKeyword"
        @create="handleCreateRole"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { characterInfo, chatHistory } from '@/api'
import type { RoleInfo } from '@/api/interface'

// 收藏项接口
interface FavoriteItem {
  id: number
  title: string
  summary: string
  source: string
  image?: string
}
import PageHeader from './PageHeader.vue'
import HistoryList from './HistoryList.vue'
import FavoritesList from './FavoritesList.vue'
import CustomRolesList from './CustomRolesList.vue'

const props = defineProps<{
  activeTab: string
}>()

// 搜索关键词
const historySearchKeyword = ref('')
const favoritesSearchKeyword = ref('')
const customRolesSearchKeyword = ref('')

// 自定义角色相关状态
const customRolesItems = ref<RoleInfo[]>([])
const customRolesLoading = ref(false)
const customRolesError = ref('')

// 对话过的角色（最近发言摘要）
const historyItems = ref<{ 
  id: number; 
  title: string; 
  summary: string; 
  time: string;
  characterId?: number | string;
  chatId?: string;
  characterName?: string;
  avatarUrl?: string;
}[]>([])

function formatTime(iso: string | null | undefined) {
  if (!iso) return ''
  try {
    const d = new Date(iso)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    const hh = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    return `${y}-${m}-${day} ${hh}:${mm}`
  } catch {
    return String(iso)
  }
}

const fetchHistoryFirstList = async () => {
  try {
    const res: any = await chatHistory.firstList()
    const list: any[] = Array.isArray(res?.data) ? res.data : []
    historyItems.value = list.map((it) => ({
      id: it.id,
      title: it.content || '对话记录',
      summary: it.content || '',
      time: formatTime(it.updateTime || it.createTime),
      characterId: it.characterId,
      chatId: it.chatId,
      characterName: it.characterName,
      avatarUrl: it.avatarUrl
    }))
  } catch (e) {
    console.error('获取对话过的角色列表失败:', e)
    historyItems.value = []
  }
}

// 收藏列表
const favoriteItems = ref<FavoriteItem[]>([])
const favoritesLoading = ref(false)
const favoritesError = ref('')

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    favoritesLoading.value = true
    favoritesError.value = ''
    
    const response = await characterInfo.favorites()
    
    if (response.code === 0 && response.data) {
      favoriteItems.value = response.data.map((item: any) => ({
        id: item.id,
        title: item.name,
        summary: item.intro || '',
        source: '对话历史',
        image: item.image || ''
      }))
    } else {
      favoritesError.value = response.message || '获取收藏列表失败'
      favoriteItems.value = []
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    favoritesError.value = '获取收藏列表失败'
    favoriteItems.value = []
  } finally {
    favoritesLoading.value = false
  }
}

// 获取自定义角色列表
const fetchCustomRoles = async (keyword?: string) => {
  try {
    customRolesLoading.value = true
    customRolesError.value = ''
    
    const params = {
      category: '自定义',
      pageNum: 1,
      pageSize: 50,
      ...(keyword && { keyword })
    }
    
    const response: any = await characterInfo.list(params)
    
    if (response.code === 0 && response.data) {
      customRolesItems.value = response.data.list || []
    } else {
      customRolesError.value = (response.message || '获取角色列表失败')
      customRolesItems.value = []
    }
  } catch (error) {
    console.error('获取自定义角色列表失败:', error)
    customRolesError.value = '网络请求失败，请稍后重试'
    customRolesItems.value = []
  } finally {
    customRolesLoading.value = false
  }
}

// 搜索防抖定时器
let searchTimer: NodeJS.Timeout | null = null

// 监听搜索关键词变化
watch(customRolesSearchKeyword, (newKeyword) => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    fetchCustomRoles(newKeyword)
  }, 500)
})

// 组件挂载时统一通过 Promise.all 获取，避免重复请求

// 处理搜索
const handleHistorySearch = (keyword: string) => {
  historySearchKeyword.value = keyword
}

const handleFavoritesSearch = (keyword: string) => {
  favoritesSearchKeyword.value = keyword
}

const handleCustomRolesSearch = (keyword: string) => {
  customRolesSearchKeyword.value = keyword
  // 搜索会通过watch自动触发fetchCustomRoles
}

// 处理收藏操作
const handleAddToFavorites = (item: any) => {
  // 添加到收藏列表
  const favoriteItem = {
    id: Date.now(),
    title: item.title,
    summary: item.summary,
    source: '对话历史'
  }
  favoriteItems.value.unshift(favoriteItem)
}

// 打开某条历史对应的对话页
const handleOpenHistory = (item: any) => {
  // 优先使用 characterId 跳转详情页
  if (item.characterId) {
    window.location.href = `/details/${item.characterId}`
    return
  }
  // 兜底：没有 characterId 时跳转到对话页并附带 chatId
  if (item.chatId) {
    window.location.href = `/details/${item.chatId}`
    return
  }
}

// 处理取消收藏
const handleRemoveFromFavorites = (item: any) => {
  const index = favoriteItems.value.findIndex(fav => fav.id === item.id)
  if (index > -1) {
    favoriteItems.value.splice(index, 1)
  }
}

// 处理自定义角色操作
const handleCreateRole = () => {
  // 跳转到新增角色页面
  window.location.href = '/create-role'
}

// 处理打开收藏的角色
const handleOpenFavorite = (item: any) => {
  // 跳转到角色详情页
  window.location.href = `/details/${item.id}`
}

// 数据获取状态管理
const dataFetched = ref({
  history: false,
  favorites: false,
  customRoles: false
})

// 组件挂载时获取所有数据
onMounted(async () => {
  console.log('ContentArea 组件挂载，开始获取数据...')
  
  // 并行获取所有数据
  await Promise.all([
    fetchHistoryFirstList(),
    fetchFavorites(),
    fetchCustomRoles()
  ])
  
  // 标记所有数据已获取
  dataFetched.value = {
    history: true,
    favorites: true,
    customRoles: true
  }
  
  console.log('所有数据获取完成')
})

// 监听 activeTab 变化，切换标签时重新获取对应数据
watch(() => props.activeTab, async (newTab) => {
  console.log('标签页切换到:', newTab)
  
  switch (newTab) {
    case 'history':
      // 只有在数据未获取时才重新获取，避免重复请求
      if (!dataFetched.value.history) {
        await fetchHistoryFirstList()
        dataFetched.value.history = true
      }
      break
    case 'favorites':
      if (!dataFetched.value.favorites) {
        await fetchFavorites()
        dataFetched.value.favorites = true
      }
      break
    case 'custom-roles':
      if (!dataFetched.value.customRoles) {
        await fetchCustomRoles()
        dataFetched.value.customRoles = true
      }
      break
  }
})

// 监听页面可见性变化和路由变化，当页面重新可见时刷新对话历史
onMounted(() => {
  const handleVisibilityChange = () => {
    if (!document.hidden && props.activeTab === 'history') {
      console.log('页面重新可见，刷新对话历史')
      fetchHistoryFirstList()
    }
  }
  
  const handlePageRefresh = () => {
    console.log('收到页面刷新事件，刷新对话历史')
    fetchHistoryFirstList()
  }
  
  document.addEventListener('visibilitychange', handleVisibilityChange)
  window.addEventListener('my-page-refresh', handlePageRefresh)
  
  // 清理事件监听器
  onUnmounted(() => {
    document.removeEventListener('visibilitychange', handleVisibilityChange)
    window.removeEventListener('my-page-refresh', handlePageRefresh)
  })
})
</script>
